package com.boot.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.common.to.seckill.SecKillSkuRelation;
import com.boot.common.to.seckill.SkuInfoTo;
import com.boot.common.utils.R;
import com.boot.mall.product.entity.SkuImagesEntity;
import com.boot.mall.product.entity.SpuInfoDescEntity;
import com.boot.mall.product.feign.SecKillFeignService;
import com.boot.mall.product.service.*;
import com.boot.mall.product.vo.SecKillVo;
import com.boot.mall.product.vo.SkuItemVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.common.utils.PageUtils;
import com.boot.common.utils.Query;

import com.boot.mall.product.dao.SkuInfoDao;
import com.boot.mall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private SecKillFeignService secKillFeignService;

    @Override
    public PageUtils pageSkuProductByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        // 获取参数
        String key = params.get("key").toString();
        String min = params.get("min").toString();
        String max = params.get("max").toString();
        String brandId = params.get("brandId").toString();
        String catelogId = params.get("catelogId").toString();
        String curr = (String) params.get("page");
        long current = 1;
        if (curr != null) {
            current = Integer.parseInt(curr);
        }
        long limit = 1;
        String limitStr = (String) params.get("limit");
        if (limitStr != null) {
            limit = Integer.parseInt(limitStr);
        }
        //判空拼接对象
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper) -> {
                wrapper.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        if (!StringUtils.isEmpty(min) && !"0".equalsIgnoreCase(min)){
            queryWrapper.ge("price",min);
        }
        if (!StringUtils.isEmpty(max) && !"0".equalsIgnoreCase(max)){
            queryWrapper.le("price",max);
        }
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        // 创建分页对象
        Page<SkuInfoEntity> page = new Page<>(current,limit);
        // 执行查询
        baseMapper.selectPage(page,queryWrapper);
        // 结果封装
        PageUtils pageUtils = new PageUtils(page.getRecords(),(int)page.getTotal(),(int)page.getSize(),(int)current);
        return pageUtils;
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id",spuId));
    }

    // 异步编排
    @Override
    public SkuItemVo findItemBySkuId(Long skuId) throws ExecutionException, InterruptedException {

        ObjectMapper mapper = new ObjectMapper();
        SkuItemVo skuItemVo = new SkuItemVo();


        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // 1.获取Sku的基本信息 pms_sku_info
            SkuInfoEntity skuInfoEntity = this.getById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            // 2.sku的图片信息 pms_sku_images
            List<SkuImagesEntity> imagesEntities = skuImagesService.getSkuImagesBySkuId(skuId);
            skuItemVo.setImages(imagesEntities);
        }, executor);

        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 3.获取spu的销售属性组合
            List<SkuItemVo.SkuItemSaleAttr> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttrs(saleAttrs);
        }, executor);

        CompletableFuture<Void> spuInfoFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 4.获取spu的介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> groupAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 5.获取spu的规格参数信息
            List<SkuItemVo.SpuItemGroupAttr> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(groupAttrs);
        }, executor);

        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
            // 6.查询sku的秒杀信息
            R res = secKillFeignService.getSkuSecKillInfo(skuId);
            if (res.getCode() == 0) {
                SecKillVo data = JSON.parseObject((String) res.get("data"), SecKillVo.class);
//                SecKillVo data = mapper.convertValue(res.get("data"), SecKillVo.class);
                skuItemVo.setSecKillVo(data);
            }
        }, executor);

        // 阻塞等待所有的异步任务完成
        CompletableFuture.allOf(imagesFuture,saleAttrFuture,spuInfoFuture,groupAttrFuture,secKillFuture).get();

        return skuItemVo;
    }

    /**
     * 查询当前Sku的最新价格信息
     * @param skuId
     * @return
     */
    @Override
    public BigDecimal getSkuCurrentPrice(Long skuId) {
        SkuInfoEntity infoEntity = this.getOne(new QueryWrapper<SkuInfoEntity>().eq("sku_id", skuId));
        return infoEntity.getPrice();
    }

    /**
     * 批量查询sku的基本信息
     * @param ids
     * @return
     */
    @Override
    public Map<String,Object> getSkuInfoBySkuIds(List<String> ids) {
        List<SkuInfoEntity> skuInfoEntities = baseMapper.selectBatchIds(ids);
        Map<String,Object> map = new HashMap<>();
        for (SkuInfoEntity infoEntity : skuInfoEntities) {
            map.put(infoEntity.getSkuId().toString(),infoEntity);
        }
        return map;
    }
}